// pages/log/log.js
import {
  Toast,
  Loading
} from "../../utils/util";
import dayjs from '../../utils/dayjs'
import echarts from '../../ec-canvas/echarts'
let chartSearch = {}
let chart = null
async function initChartOne(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 像素
  });
  canvas.setChart(chart);
  const _ = wx.cloud.database().command;
  const res = await wx.cloud.database().collection('todoList').where({
    sportTimeStr: _.and(_.gt(chartSearch.startTime), _.lt(chartSearch.endTime)),
    userId: wx.getStorageSync('uid'),
    tableType: "sport"
  }).get()
  let sportList = []
  res.data.map(item => item.sportData.data).forEach(it => {
    sportList = sportList.concat(it)
  })
  console.log(sportList, '我要')
  const groupedData = sportList.reduce((acc, obj) => {
    const key = obj.value;
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
  console.log(groupedData, '外部')
  let optionArray = [];
  Object.keys(groupedData).forEach(item => {
    let arr = groupedData[item].map(items => parseInt(items.time))
    let prices = arr.reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0)
    optionArray.push({
      name: item,
      value: prices
    })
  })
  console.log(optionArray, '外部2')
  var option = {
    title: {
      text: `运动记录占比`,
      left: 'center',
      top: "0"
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)' // 默认显示数值和百分比
    },
    legend: {
      left: 'center',
      bottom: '0px'
    },
    label: {
      show: true,
      formatter: '{b}: {c} \n({d}%)', // 显示名称、数值、百分比
      position: 'outside',
      color: 'black'
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '40%',
        center: ['50%', '50%'],
        data: [...optionArray],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chart.setOption(option);
  console.log(chart)
  return chart;
}
Page({
  backBtn: function () {
    wx.navigateBack()
  },

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      onInit: {}
    },
    searchTime: "",
    form: {},
    walkTime: wx.getStorageSync('walkTime') > 0 ? wx.getStorageSync('walkTime') : 0,
    runTime: wx.getStorageSync('runTime') > 0 ? wx.getStorageSync('runTime') : 0,
    jumpTime: wx.getStorageSync('jumpTime') > 0 ? wx.getStorageSync('jumpTime') : 0,
    circleTime: wx.getStorageSync('circleTime') > 0 ? wx.getStorageSync('circleTime') : 0,
    ballTime: wx.getStorageSync('ballTime') > 0 ? wx.getStorageSync('ballTime') : 0,
    bikeTime: wx.getStorageSync('bikeTime') > 0 ? wx.getStorageSync('bikeTime') : 0,
    tiaoTime: wx.getStorageSync('tiaoTime') > 0 ? wx.getStorageSync('tiaoTime') : 0,
    energyTime: wx.getStorageSync('energyTime') > 0 ? wx.getStorageSync('energyTime') : 0,
    countTime: wx.getStorageSync('countTime') > 0 ? wx.getStorageSync('countTime') : 0
  },
  async reLoadDateChart() {
    const _ = wx.cloud.database().command;
    const res = await wx.cloud.database().collection('todoList').where({
      sportTimeStr: _.and(_.gt(chartSearch.startTime), _.lt(chartSearch.endTime)),
      userId: wx.getStorageSync('uid'),
      tableType: "sport"
    }).get()
    let sportList = []
    res.data.map(item => item.sportData.data).forEach(it => {
      sportList = sportList.concat(it)
    })
    const groupedData = sportList.reduce((acc, obj) => {
      const key = obj.value;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    let optionArray = [];
    Object.keys(groupedData).forEach(item => {
      let arr = groupedData[item].map(items => parseInt(items.time))
      let prices = arr.reduce(function (accumulator, currentValue) {
        return accumulator + currentValue;
      }, 0)
      optionArray.push({
        name: item,
        value: prices
      })
    })
    var option = {
      title: {
        text: `运动记录占比`,
        left: 'center',
        top: "0"
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)' // 默认显示数值和百分比
      },
      legend: {
        left: 'center',
        bottom: '0px'
      },
      label: {
        show: true,
        formatter: '{b}: {c}\n ({d}%)', // 显示名称、数值、百分比
        position: 'outside',
        color: 'black'
      },
      series: [
        {
          name: '占比',
          type: 'pie',
          radius: '40%',
          center: ['50%', '50%'],
          data: [...optionArray],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    chart.setOption(option);
  },
  reduceWeek() {
    this.setData({
      searchTime: `${dayjs(new Date(this.data.searchTime.split(' - ')[0])).subtract(1, "week").format('YYYY/MM/DD')} - ${dayjs(new Date(this.data.searchTime.split(' - ')[1])).subtract(1, "week").format('YYYY/MM/DD')}`,
      "ec.onInit": {}
    })
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }
    this.reLoadDateChart()
  },
  addWeek() {
    this.setData({
      searchTime: `${dayjs(new Date(this.data.searchTime.split(' - ')[0])).add(1, "week").format('YYYY/MM/DD')} - ${dayjs(new Date(this.data.searchTime.split(' - ')[1])).add(1, "week").format('YYYY/MM/DD')}`,
      "ec.onInit": {}
    })
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }
    this.reLoadDateChart()
  },
  getSportToWeek() {
    chartSearch = {
      startTime: dayjs().startOf("week").valueOf(),
      endTime: dayjs().endOf("week").valueOf(),
    }
    this.setData({
      searchTime: `${dayjs().startOf("week").format('YYYY/MM/DD')} - ${dayjs().endOf("week").format('YYYY/MM/DD')}`,
      "ec.onInit": initChartOne,
    })
  },
  async getAddSportStatus() {
    const res = await wx.cloud.database().collection('todoList').where({
      sportTime: dayjs(new Date()).format('YYYY-MM-DD'),
      userId: wx.getStorageSync('uid'),
    }).get()
    this.setData({
      form: res.data[0]
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAddSportStatus()
    this.getSportToWeek()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      walkTime: wx.getStorageSync('walkTime') > 0 ? wx.getStorageSync('walkTime') : 0,
      runTime: wx.getStorageSync('runTime') > 0 ? wx.getStorageSync('runTime') : 0,
      jumpTime: wx.getStorageSync('jumpTime') > 0 ? wx.getStorageSync('jumpTime') : 0,
      circleTime: wx.getStorageSync('circleTime') > 0 ? wx.getStorageSync('circleTime') : 0,
      ballTime: wx.getStorageSync('ballTime') > 0 ? wx.getStorageSync('ballTime') : 0,
      bikeTime: wx.getStorageSync('bikeTime') > 0 ? wx.getStorageSync('bikeTime') : 0,
      tiaoTime: wx.getStorageSync('tiaoTime') > 0 ? wx.getStorageSync('tiaoTime') : 0,
      energyTime: wx.getStorageSync('energyTime') > 0 ? wx.getStorageSync('energyTime') : 0,
      countTime: wx.getStorageSync('countTime') > 0 ? wx.getStorageSync('countTime') : 0
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})